//
//  HomeRefresh.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/7/23.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit
import FFAutoLayout


///刷新控件
class HomeRefresh: UIRefreshControl {

    override init() {
        super.init()
        addSubview(refreshView)
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 120, height: 60))
        //KVO监听
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
    }
    ///注销监听
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
        
    }
    
    private var showTipFlag = false
    //正在加载标记
    private var loadingFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0{
            return
        }
        
        if  refreshing && !loadingFlag {
            refreshView.startLoadingAnim()
            loadingFlag = true
            return
        }
        if frame.origin.y < -50 && !showTipFlag{
            showTipFlag = true
            refreshView.rotateTipIcon(showTipFlag)
            
        }else if frame.origin.y >= -50 && showTipFlag{
            showTipFlag = false
            refreshView.rotateTipIcon(showTipFlag)
        }
    }

    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stoploadingAnim()
        loadingFlag = false
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var refreshView = HomeRefreshView.refreshView()
}


///刷新视图
//旋转技巧
class HomeRefreshView:UIView{
    
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var loadIcon: UIImageView!
    class func refreshView() -> HomeRefreshView{
return NSBundle.mainBundle().loadNibNamed("HomeRefreshView", owner: nil, options: nil).last as! HomeRefreshView
        
    }
    //选择技巧
    private func rotateTipIcon(clockWise:Bool){
        var angle = M_PI
        angle += clockWise ? -0.01:0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform,CGFloat(angle))
        }
    }
    ///开启加载动画
    private func  startLoadingAnim() {
        
        tipView.hidden = true
        
        let  anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        loadIcon.layer.addAnimation(anim, forKey: nil)
        
    }
    //停止动画
    private func stoploadingAnim(){
        loadIcon.layer.removeAllAnimations()
        tipView.hidden = false
    }
    
    
}